package managers;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import entities.DeviceNC;
import entities.DevicePair;


@Stateless
@LocalBean
public class DeviceManager {
	@PersistenceContext
	EntityManager em;
	
	public DeviceNC Create(DeviceNC d){
		em.persist(d);
		em.flush();
		return d;
	}
	
	public DeviceNC Update(DeviceNC d){
		em.merge(d);
		em.flush();
		return d;
	}
	
	public void removeDevice(String uuid){
		DeviceNC d = getDevice(uuid, false);
		if(d != null){
			em.remove(d);
			em.flush();
		}
	}
	
	public DeviceNC getDevice(String uuid, boolean isIp){
		DeviceNC d = null;
		if(!isIp){
			d = em.getReference(DeviceNC.class, uuid);
//			TypedQuery<DeviceNC> query = em.createQuery("SELECT d FROM DevicesNC d WHERE d.uuid = '" + uuid + "'", DeviceNC.class); 
//			List<DeviceNC> devices = query.getResultList();
//			d = devices.get(0);
		}else{
			TypedQuery<DeviceNC> devicesQuery = em.createQuery("SELECT d FROM DeviceNC d WHERE d.ip = '" + uuid + "'", DeviceNC.class);
			List<DeviceNC> devices = devicesQuery.getResultList();
			d = devices.get(0);
		}
		return d;
	}
	public List<DeviceNC> getDevices(){
		List<DeviceNC> devices = new ArrayList<DeviceNC>();
		
		TypedQuery<DeviceNC> devicesQuery = em.createQuery("SELECT d FROM DeviceNC d", DeviceNC.class);
		for(DeviceNC d : devicesQuery.getResultList()){
			devices.add(d);
		}
		
		return devices;
	}
	
	public String getDevicePairKey(String uuid){
		String pairKey = "";
		
		Query query = em.createQuery("SELECT p.device_pairkey FROM DevicePair p WHERE p.device_uuid = '" + uuid + "'", DevicePair.class);
		pairKey = query.getSingleResult().toString();
		
		return pairKey;
	}
}
